package test;

/**
 * @Description 三只小狗抢100根香肠，一次只能有一只抢成功；直到抢完为止，统计每只小狗抢了多少
 * @Author Firenut
 * @Date 2023-09-04 14:48
 */
public class DogThread extends Thread {
    static volatile int num = 100;
    static Object obj = new Object();
    private int count;

    @Override
    public void run() {
        while (num > 0) {
            synchronized (obj) {
                if (num > 0) {
                    num--;
                    count++;
                }
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        DogThread d1 = new DogThread();
        DogThread d2 = new DogThread();
        DogThread d3 = new DogThread();

        d1.start();
        d2.start();
        d3.start();

        try {
            d1.join();
            d2.join();
            d3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(d1.count);
        System.out.println(d2.count);
        System.out.println(d3.count);
    }
}
